BaseClassHelper = {}

-- 人拥有玩具: person_ins.toy = toy_ins
-- 玩具属于人: toy_ins.person = person_ins  这样就会产生循环强引用
-- 玩具属于人: toy_ins:GetWeak().person = person_ins  解除循环强引用
function BaseClassHelper.GetWeak(self)
    if not self.weak then
        self.weak = {}
        setmetatable(self.weak, {__mode = "v" })
    end
    return self.weak
end

BaseClassHelper._CanDeleteMeTypes = {["table"] = true, ["userdata"] = true, ["function"] = true}
function BaseClassHelper.DeleteMe(self)
	if self._use_delete_method then
		return
	end
	self._use_delete_method = true--预防循环释放

	local now_super = self._class_type 
	while now_super ~= nil do	
		if now_super.__delete then
			now_super.__delete(self)
		end
		now_super = now_super.super
	end

	--print("Delete", self)
	if self.InstantiateTable then
		for index = 1, #self.InstantiateTable do
            local instantiate_elem = self.InstantiateTable[index]
			if instantiate_elem then -- and not instantiate_elem._use_delete_method then
				--if instantiate_elem.DeleteMe then
					instantiate_elem:DeleteMe()
				--end
			end
		end
		self.InstantiateTable = nil
	end

	--解除引用（兼容老的写法，新写法不用管）
	for k,v in pairs(self) do
		if k and v then
			if k ~= "_class_type" and k ~= "_obj_unique_id" then
				if BaseClassHelper._CanDeleteMeTypes[type(v)]  then
					self[k] = nil
				end
			end
		end
	end

	self._use_delete_method = true--清了要再赋值
end
		

 function BaseClassHelper.Instantiate(self, class, object, ...)
	if not self.InstantiateTable then
		self.InstantiateTable = {}
	end
    local ins = EngineTools.Instantiate(class, object, ...)
	table.insert(self.InstantiateTable, ins)
	return ins
end

if false then
	 function BaseClassHelper.NewIndex(tab, k, v)
		if type(v) == "table" and v._class_type then
			for key, val in pairs(v) do
				if type(val) == "table" and val._class_type then
					if tab == val then
						warning("<color=red>循环强引用</color>:", tab,".", k, "  =引用=>  ", v, ".", key, "=引用前者=↓")
					end
				end
			end
		end
		rawset(tab, k, v)
	end
end